package top.lingkang.mm.solon;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.session.SqlSessionFactory;
import org.noear.solon.Solon;
import org.noear.solon.core.AppContext;
import org.noear.solon.core.Plugin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.lingkang.mm.annotation.MagicMapper;

/**
 * @author lingkang
 * @create by 2024/3/4 15:27
 */
public class MagicMybatisPlugin implements Plugin {
    private static final Logger log = LoggerFactory.getLogger(MagicMybatisPlugin.class);

    @Override
    public void start(AppContext context) throws Throwable {
        if (Solon.app().enableTransaction()
                && context.cfg().get("mybatis.magic.close-default-tran", "true").equals("true")) {
            Solon.app().enableTransaction(false);
            log.info("mybatis-magic 将关闭默认事务插件，您可以配置：mybatis.magic.close-default-tran=false 取消");
        }
        // 需要加载 SqlSessionFactory 后
        context.subWrapsOfType(SqlSessionFactory.class, beanWrap -> {
            context.beanBuilderAdd(MagicMapper.class, new MapperBeanBuilder(beanWrap.get()));
            context.beanBuilderAdd(Mapper.class, new Mapper2BeanBuilder(beanWrap.get()));

            TransactionalInterceptor interceptor = new TransactionalInterceptor();
            context.beanInterceptorAdd(Transactional.class, interceptor, 121);
        });
    }
}
